﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace FireUI.Themes.WPF.Controls;

public class Ripple : ContentControl
{
    static Ripple()
    {
        DefaultStyleKeyProperty.OverrideMetadata(
            typeof(Ripple),
            new FrameworkPropertyMetadata(typeof(Ripple))
        );
    }

    public Ripple()
    {
        this.SizeChanged += OnSizeChanged;
    }

    private void OnSizeChanged(object sender, SizeChangedEventArgs e)
    {
        var radius = Math.Sqrt(ActualWidth * ActualWidth + ActualHeight * ActualHeight);
        RippleX = 2 * radius;
        RippleY = 2 * radius;
        if (GetTemplateChild("border") is Border border)
        {
            RectangleGeometry rectangleGeometry = new RectangleGeometry
            {
                RadiusX = border.CornerRadius.TopLeft,
                RadiusY = border.CornerRadius.TopRight,
                Rect = new Rect(0, 0, ActualWidth, ActualHeight)
            };
            border.Clip = rectangleGeometry;
        }
    }

    protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
    {
        var point = e.GetPosition(this);
        Center = new Point(point.X - RippleX / 2, point.Y - RippleY / 2);
        base.OnMouseLeftButtonDown(e);
    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
    }

    #region DependencyProperty

    #region DependencyProperty : Center

    public Point Center
    {
        get { return (Point)GetValue(CenterProperty); }
        set { SetValue(CenterProperty, value); }
    }

    public static readonly DependencyProperty CenterProperty = DependencyProperty.Register(
        "Center",
        typeof(Point),
        typeof(Ripple),
        new PropertyMetadata(default(Point))
    );

    #endregion DependencyProperty : Center

    #region DependencyProperty : RippleX

    public double RippleX
    {
        get { return (double)GetValue(RippleXProperty); }
        set { SetValue(RippleXProperty, value); }
    }

    public static readonly DependencyProperty RippleXProperty = DependencyProperty.Register(
        "RippleX",
        typeof(double),
        typeof(Ripple),
        new PropertyMetadata(default(double))
    );

    #endregion DependencyProperty : RippleX

    #region DependencyProperty : RippleY

    public double RippleY
    {
        get { return (double)GetValue(RippleYProperty); }
        set { SetValue(RippleYProperty, value); }
    }

    public static readonly DependencyProperty RippleYProperty = DependencyProperty.Register(
        "RippleY",
        typeof(double),
        typeof(Ripple),
        new PropertyMetadata(default(double))
    );

    #endregion DependencyProperty : RippleY

    #endregion DependencyProperty
}
